<template>
	<view class="padding_48rpx">
		<view class="myNmae flex-between">
			<text style="min-width: 150rpx;">展示区域</text>
			<picker mode="selector" @change='region' :range="regionList" :range-key="'text'">
				<view class="flex">
					<text>{{selsectRegion}}</text>
					<uni-icons type="right" size="15"></uni-icons>
				</view>
			</picker>
		</view>
		<view class="myNmae flex-between margin-top_60rpx">
			<text style="min-width: 150rpx;">轮播图排序</text>
			<input type="number" v-model="form.sort" placeholder="轮播图排序" />
		</view>
		<view class="myNmae flex-between margin-top_60rpx">
			<text style="min-width: 160rpx;">跳转方式</text>
			<view style="margin-right:0rpx;" class="">
				<radio-group style="transform:scale(0.8) " @change="radioChange" class="flex-start-center ">
					<label class="flex-start-center  margin-right_16rpx" v-for="(item, index) in items"
						:key="item.value">
						<view>
							<radio :value="item.value" :checked="index == current" />
						</view>
						<view>{{item.name}}</view>
					</label>
				</radio-group>
			</view>
		</view>
		<view class="" v-if="form.jump_way==1">
			<view class="myNmae flex-between margin-top_60rpx">
				<text style="min-width: 160rpx;">本地路径</text>
				<input v-model="form.link" placeholder="请输入本地路径" />
			</view>

		</view>
		<view class="" v-if="form.jump_way==2">
			<view class="myNmae flex-between margin-top_60rpx">
				<text style="min-width: 160rpx;">链接</text>
				<input v-model="form.link" placeholder="请输入链接" />
			</view>

		</view>
		<view class="" v-if="form.jump_way==3">
			<view class="myNmae flex-between margin-top_60rpx">
				<text style="min-width: 160rpx;">小程序原始ID</text>
				<input v-model="form.applet_id" placeholder="请输入小程序原始ID" />
			</view>
			<view class="myNmae flex-between margin-top_60rpx">
				<text style="min-width: 160rpx;">小程序路径</text>
				<input v-model="form.link" placeholder="请输入小程序路径" />
			</view>
		</view>
		<sunui-upimg1 class="margin-top_20rpx" :border="'1px dashed #bfbfbf'" :formData="imgFormData"
			:storageMode="storageMode" :header="header" :size="['200rpx', '200rpx']" btnName="上传轮播图"
			:uploadServerUrl="upPicUrl" ref="selectimgandupload1" @uploaded="imgLoaded1" @change="imgsChange1"
			:maxFileNumber="1"><template v-slot:icon>
				<uni-icons type="camera-filled" color="#1890FF" size="40"></uni-icons>
			</template></sunui-upimg1>
		<view class="btnSure flex" @click="newAdd()">

			{{isEdit?'编辑':'立即添加'}}
		</view>

	</view>
</template>

<script>
	import {
		object2Url
	} from '@/utils/trans';
	export default {
		components: {

		},
		data() {
			return {
				tabIndex: 4,

				regionList: [{
					text: '首页',
					value: '1'

				}, {
					text: '商城',
					value: '2'

				}, {
					text: '套餐',
					value: '3'

				}, ],
				changeValue: '',

				imgFormData: null,
				ossInfo: null,
				upPicUrl: null,
				imgStr: [],
				isEdit: false,
				storageMode: "2",
				header: null,
				form: {
					// 展示区域  1 首页 2 商城 3 套餐卡市场
					type: '',
					// 跳转链接
					link: '',
					// 排序
					sort: '',
					// 图片
					img: '',
					// 跳转方式 1 跳本地 ， 2 跳h5 ，3 跳小程序
					jump_way: '2',

					applet_id: ''
					// xcxPath: '',
					// originalID: '',
					// localPath: ''
				},
				items: [
					// {
					// 	value: '1',
					// 	name: '跳本地',
					// 	checked: 'true'
					// },
					{
						value: '2',
						name: '跳h5'
					},
					// {
					// 	value: '3',
					// 	name: '跳小程序'
					// },


				],
				token: uni.getStorageSync('login').token,
				// 选中的区域
				selsectRegion: '请选择',
				current: 0
			}
		},
		onLoad(options) {
			if (options.id) {
				this.form.id = ''

				this.$sun.assignObject(this.form, {
					...options
				})


				this.isEdit = true
				this.$nextTick(() => {
					this.$refs.selectimgandupload1.setItems([options.img]);
				})
				const couponType = this.regionList.find((item) => {
					return item.value == this.form.type
				})

				this.selsectRegion = couponType.text
				console.log(this.form.jump_way)
				if (this.form.jump_way == '1') {
					this.current = 0
				} else if (this.form.jump_way == '2') {
					console.log('jinr111111111')
					this.current = 1
				} else {
					this.current = 2
				}
				console.log(this.form)
			}
		},
		onShow() {
			// console.log(uni.getStorageSync('login').token)
			this.$at.releaseKey('submit');
		},
		methods: {

			// 展示区域
			region(e) {
				console.log(e)
				this.selsectRegion = this.regionList[e.detail.value].text
				this.form.type = this.regionList[e.detail.value].value
			},
			// 跳转方式
			radioChange(e) {
				// 
				this.form.jump_way = e.detail.value
				this.form.link = ''
				this.form.applet_id = ''
			},
			// 添加轮播图
			newAdd() {
				console.log(this.form)
				this.$at.uniDoFunc({
					key: 'submit',
					success: async () => {
						this.$at.lockKey('submit');
						// 登录 需要进行判断当前账号密码 和账号归属店铺及角色是否又选择
						if (!this.form.type) {
							this.$sun.toast("请选择展示区域", 'none')
							this.$at.releaseKey('submit');
						} else if (!this.form.sort) {
							this.$sun.toast("请填写轮播图", 'none')
							this.$at.releaseKey('submit');
						} else if (this.form.jump_way) {
							console.log(this.form.jump_way)
							if (!this.form.link && this.form.jump_way == 1) {
								this.$sun.toast('请填写本地路径', 'none');
								this.$at.releaseKey('submit');
							} else if (!this.form.link && this.form.jump_way == 2) {
								this.$sun.toast('请填写h5链接', 'none');
								this.$at.releaseKey('submit');
							} else if (!(this.form.link && this.form.applet_id) && this.form.jump_way ==
								3) {

								this.$sun.toast('请填写小程序路径和原始id', 'none');
								this.$at.releaseKey('submit');
							} else {


								const saveOrUpdate = this.isEdit ? this.$api.editPoster : this.$api.addPoster;
								const res = await this.$http.post({
									url: saveOrUpdate,
									data: {

										...this.form
									},
									headers: {
										'Authorization': `Bearer ${this.token}`
									}

								})
								console.log(res)
								if (res.code == 0) {

									this.$sun.toast(res.msg, 'none')

									// 跳转到登录页面
									this.$at.releaseKey('submit');

									setTimeout(() => {
										this.$sun.navBack()
									}, 500)

								} else {
									this.$at.releaseKey('submit');
									this.$sun.toast(res.msg, 'none')
								}
							}

						}
					}
				});
			},
			// niuyun
			niuyunLoop(file, i) {
				if (i >= file.length) {
					return;
				}
				console.log(file)
				let fileUrl = file[i].url;
				this.upPicUrl = this.$api.qnyOssSignature;
				let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
				this.imgFormData = {
					file: fileUrl,
					getsize: file.size,
					getContentType: ['image/png', 'image/jpeg'],
					getoriginalfilename: filesNmae,
					getName: filesNmae
				};
				this.$nextTick(() => {
					this.$refs.selectimgandupload1.upload(); //图片上传
				});
				setTimeout(() => {
					this.niuyunLoop(file, i + 1);
				}, 2500);

			},
			delayLoop(file, i) {
				if (i >= file.length) {
					return;
				}
				console.log(file.length + '===chand1')
				if (file.length) {
					let fileUrl = file[i].url;
					console.log(fileUrl)
					this.timeDate = new Date().getTime();
					let markIndex = fileUrl.lastIndexOf('.');
					this.suffix = fileUrl.substring(markIndex); //后缀


					this.imgFormData = {
						name: this.timeDate + this.suffix,
						key: this.timeDate + this.suffix, //上传图片的名字和路径（默认路径根目录，自定义目录：xxx/xxx.png）
						policy: this.ossInfo.policy,
						OSSAccessKeyId: this.ossInfo.accessId,
						success_action_status: '200',
						signature: this.ossInfo.signature
					};
					this.header = {
						'Access-Control-Allow-Origin': '*',
						'x-oss-callback-Authorization': 'access_token'
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload1.upload(); //图片上传
					});

				} else {
					this.form.img = ''
				}

				setTimeout(() => {
					this.delayLoop(file, i + 1);
				}, 500);
			},
			// 上传图片返回
			imgLoaded1(e) {
				console.log(e)

				this.img = [];
				for (let i = 0; i < e.length; i++) {
					this.img.push(e[i].url);
				}


				this.imgStr = this.img

				this.form.img = this.imgStr.length === 1 ? this.imgStr[0].toString() : this.imgStr
					.join(',');
			},
			// “上传图片”发生改变
			imgsChange1(file) {

				if (file.length) {
					this.upPicUrl = this.$api.upload;
					let filesNmae = 'nmoBackground_01.png'; // this.timeDate + 'png'
					this.imgFormData = {
						file: file,
						getsize: file.size,
						getContentType: ['image/png', 'image/jpeg'],
						getoriginalfilename: filesNmae,
						getName: filesNmae
					};
					this.$nextTick(() => {
						this.$refs.selectimgandupload1.upload(); //图片上传
					});
				} else {
					this.form.img = '',
						this.imgStr = []
				}
			},
			// 阿里云上传
			async userOssSignature(file) {
				// 文件名
				if (file.length) {
					console.log('this阿里云上传进入=======');
					const ts = new Date().getTime();
					const us = {
						ts
					};
					// let url = this.$api.alyOssSignature + `${object2Url(us)}`;
					let url = 'https://yjykmaster.admin168.net/door-massage/massage/upload/alyOssSignature' +
						`${object2Url(us)}`;

					const res = await this.$http.get({
						url: url,
						data: {
							us: us
						}
					});
					this.ossInfo = res.data;
					this.upPicUrl = this.ossInfo?.host;
					// 获取上传图片名称和后缀
					this.delayLoop(file, 0);
				} else {
					this.form.img = '',
						this.imgStr = []
				}




			},
		}
	}
</script>

<style lang="less" scoped>
	.edit {

		height: 54px;
		background: rgb(246, 248, 255);



	}

	.myNmae {

		background-color: #fff;
		min-width: 50rpx;

		.avatar {
			width: 84rpx;
			height: 84rpx;
		}

		input {
			text-align: right;
		}

		.backgroundImg {

			height: 154rpx;


		}

	}

	.btnSure {
		width: 655rpx;
		height: 76rpx;
		background: rgb(81, 142, 247);
		color: rgb(255, 255, 255);
		border-radius: 108rpx;
		font-size: 32rpx;
		font-weight: 700;
		position: fixed;
		bottom: 20rpx;
	}

	page {
		background: #fff;
	}
</style>